package YAPclient;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import YAPenvironment.YAPconstant;

/**
 * This class is used to enable the discovery function when a client is started.
 */

public class DiscoveryClient extends Thread{
	
	private static DatagramSocket DS_socketOut;
	private static DatagramSocket DS_socketIn;
	private static DatagramPacket DP_out;
	private static DatagramPacket DP_in;

	private static boolean run=true;
	
	DiscoveryClient(){
		try{
			DS_socketOut = new DatagramSocket(YAPconstant.C_MULTICASTPORT1);
			DS_socketIn  = new DatagramSocket(YAPconstant.C_MULTICASTPORT2);
			
			this.start();
			new ListActualizer();
		}catch (Exception e){
			if(YAPconstant.C_DEBUG){ e.printStackTrace(); }
			System.out.println("Discovery couldn't be enabled.");
		}
		
		
	}
	
	public void close(){
		try{
			run=false;
			DS_socketOut.close();
			DS_socketIn.close();
		}catch (Exception e){
			//ignore
		}
	}
	

	private void sendPackage() throws Exception{
		byte buf[] = ("hoi").getBytes();

		DP_out = new DatagramPacket(buf, buf.length,
					 InetAddress.getByName(YAPconstant.C_MULTICASTGROUP), YAPconstant.C_MULTICASTPORT1);

		DS_socketOut.send(DP_out);
		
		YAPgame.getServerModel().removeAllElements();
	}
	
	private void receivePackage() throws Exception{
		byte buf[] = new byte[4];
		DP_in = new DatagramPacket(buf, buf.length,
				 InetAddress.getByName(YAPconstant.C_MULTICASTGROUP), YAPconstant.C_MULTICASTPORT2);
		DS_socketIn.receive(DP_in);

		YAPgame.getServerModel().addElement(DP_in.getAddress().toString().replaceFirst("/","")+":"+new String(DP_in.getData()));
	}
	
	public void run() {
		while(run){
			try{
				sendPackage();
				Thread.sleep(3000);
			}catch (Exception e){
				if(YAPconstant.C_DEBUG){ e.printStackTrace(); }
				if(!run)
					break;
			}
		}
	}
	
	class ListActualizer extends Thread{
		ListActualizer(){
			this.start();
		}
		public void run(){
			while(run){
				try{
					receivePackage();
				}catch(SocketException e){
					//ignore
				}catch (Exception e){
					if(YAPconstant.C_DEBUG){ e.printStackTrace(); }
					if(!run)
						break;
				}
			}
		}		
	}
	
}
